package com.xiong.wuliao.homefragment;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.xiong.wuliao.R;
import com.xiong.wuliao.SpecialActivity;
import com.xiong.wuliao.adapter.MyHomeListAdapter;
import com.xiong.wuliao.entity.HomeStorys;
import com.xiong.wuliao.entity.Urls;
import com.xiong.wuliao.interfaces.OnLoveClickListener;
import com.xiong.wuliao.util.HomeJSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 涨知识Fragment
 */
public class ZhishiFragment extends Fragment implements OnLoveClickListener{
    private SwipeRefreshLayout mySwipeRefreshLayoutZhiShi;
    private ListView myListViewZhiShi;

    // 刷新后请求服务器的参数
    private int offset = 0;
    // 是否到达页面底部的标注
    private boolean isBottom = false;
    // 保存服务器传过来的数据
    private List<HomeStorys> storysList = new ArrayList<>();
    // ListView的自定义适配器
    private MyHomeListAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_zhishi, container, false);
        findView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        setMyAdapter();
        setListener();
    }

    /**
     * 设置监听
     */
    private void setListener() {
        /**
         * 上拉加载的监听
         */
        myListViewZhiShi.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE){
                    offset += 20;
                    getZhiShiServerData();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isBottom = firstVisibleItem + visibleItemCount == totalItemCount;
            }
        });

        /**
         * 下拉刷新的监听
         */
        mySwipeRefreshLayoutZhiShi.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                offset += 20;
                getZhiShiServerData();

            }
        });

        /**
         * ListView的item点击事件
         */
        myListViewZhiShi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HomeStorys storys = storysList.get(position);
                String lastId = storys.getId();
                Intent intent = new Intent(getActivity(), SpecialActivity.class);
                intent.putExtra("lastId",lastId);
                startActivity(intent);
            }
        });
    }

    /**
     * 设置适配器
     */
    private void setMyAdapter() {
        adapter = new MyHomeListAdapter(getActivity(),storysList);
        myListViewZhiShi.setAdapter(adapter);
		// 设置接口
		adapter.setLoveListener(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getZhiShiServerData();
    }

    /**
     * 保存服务器数据
     */
    private void getZhiShiServerData(){
        OkHttpUtils.get(Urls.ZhiShiPath)
                .params("gender",2)
                .params("limit",20)
                .params("offset",offset)
                .params("generation",2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(s.trim());
                            String result = jsonObject.getString("message");
                            if (result.equals("OK")){

                                storysList.addAll(HomeJSON.saveHomeStory(s.trim()));
                                adapter.notifyDataSetChanged();
                                mySwipeRefreshLayoutZhiShi.setRefreshing(false);
                            }else {
                                Toast.makeText(getActivity(),"数据请求失败",Toast.LENGTH_SHORT).show();
                                mySwipeRefreshLayoutZhiShi.setRefreshing(false);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    /**
     * 初始化控件
     */
    private void findView(View view) {
        mySwipeRefreshLayoutZhiShi = (SwipeRefreshLayout) view.findViewById(R.id.mySwipeRefreshLayoutZhiShi);
        myListViewZhiShi = (ListView) view.findViewById(R.id.myListViewZhiShi);
    }

	@Override
	public void loveClick(View view) {
		final int position = (int) view.getTag();
		if (storysList.get(position).isLiked()) {

		} else {
			SharedPreferences prefe = getActivity().getSharedPreferences("kkUser", getActivity().MODE_PRIVATE);
			String uid = "";
			uid = prefe.getString("id", "");
			if (uid.equals("")) {
				Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
			} else {
				OkHttpUtils.get(Urls.LovePath)
						.params("uid", uid)
						.params("aid", storysList.get(position).getId())
						.execute(new StringCallback() {
							@Override
							public void onSuccess(String s, Call call, Response response) {
								JSONObject jsonObject = null;
								try {
									jsonObject = new JSONObject(s.trim());
									String result = jsonObject.getString("message");
									if (result.equals("OK")) {
										storysList.get(position).setLiked(true);
										adapter.notifyDataSetChanged();
									} else {
										Toast.makeText(getActivity(), "点赞失败", Toast.LENGTH_SHORT).show();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});
			}
		}
	}
}
